package com.jhws.util;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.util.Date;

class DateSerializer implements JsonSerializer<Date> {
	public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
		return new JsonPrimitive(src.getTime());
	}
}

class DateDeserializer implements JsonDeserializer<Date> {
	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
		try {
			return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
		} catch (Exception e){
            return DateUtil.stringDate(json.getAsJsonPrimitive().getAsString());
		}
	}
}


public class GsonUtil {
	static {
		GsonBuilder builder = new GsonBuilder();
		builder.registerTypeAdapter(java.util.Date.class, new DateSerializer()).setDateFormat(DateFormat.LONG);
		builder.registerTypeAdapter(java.util.Date.class, new DateDeserializer()).setDateFormat(DateFormat.LONG);
        gsonTimeStamp = builder.create();
	}
	private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS").create();

	private static Gson gsonTimeStamp;

	public static String toJson(Object o){
		return gson.toJson(o);
	}

	public static <T> T toObject(String json, Class<T> classOfT){
		return gson.fromJson(json, classOfT);
	}

	/**
	 * 碰到Date类型数据时，将其自动转成时间戳格式
	 * @param o Bean对象
	 * @param timeStamp  true表示将Date转成时间戳,false表示不变
	 * @return
	 */
    public static String toJson(Object o,Boolean timeStamp){
	    if(timeStamp)
	        return gsonTimeStamp.toJson(o);
	    else
	        return toJson(o);
    }

    /**
     * 碰到Date类型的数据，假如json中是时间戳, 则自动转成时间格式
     * @param json
     * @param classOfT
     * @param timeStamp
     * @param <T>
     * @return
     */
    public static <T> T toObject(String json, Class<T> classOfT,Boolean timeStamp){
        if(timeStamp)
            return gsonTimeStamp.fromJson(json, classOfT);
        else
            return toObject(json,classOfT);
    }

	public static Gson getGson(){
		return gson;
	}
}	
